﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;

namespace LastfmTopDownloader
{
    /// <summary>
    /// Downoads the songs and saves them into
    /// {Path}\{ArtistName}
    /// </summary>
    public static class VkDownloader
    {
        private static Dictionary<string, string> _uniDict;
        public static string Path;

        public delegate void StatusHandler(string song);
                            public static event StatusHandler DownloadedEvent;
                            public static event StatusHandler DownloadingEvent;
                            public static event StatusHandler FaildeEvent;

        public static string OnFaildeEvent(string song)
        {
            StatusHandler handler = FaildeEvent;
            if (handler != null) handler(song);
            return song;
        }

        public static string OnDownloadingEvent(string song)
        {
            StatusHandler handler = DownloadingEvent;
            if (handler != null) handler(song);
            return song;
        }

        public static string OnDownloadedEvent(string song)
        {
            StatusHandler handler = DownloadedEvent;
            if (handler != null) handler(song);
            return song;
        }

        public static List<string> GetSongs(string artist)
        {
            return SongsTopListGetter.GetTop(artist, 15);
        }

        public static List<string> GetFailedSongs(List<string> songs, string artist)
        {
            List<string> retList = new List<string>();

            List<string> struris = (songs.Select(song => (GetFileUrl(artist, song)))).ToList();

            _uniDict = songs.ToDictionary(x => x,
                                          x =>
                                          struris[songs.IndexOf(x)].ToString(
                                              CultureInfo.InvariantCulture));

            foreach (var keyValuePair in _uniDict.Where(x => x.Value == "NoSongSuchLikeThisLOL").ToList())
            {
                retList.Add(keyValuePair.Key);
                _uniDict.Remove(keyValuePair.Key);
            }
            return retList;
        }

        public static void GetUris(string artist)
        {
            List<Uri> uris = _uniDict.Select(str => new Uri(str.Value)).ToList();

            var webClient = new WebClient();
            var dirpath = string.Format("{0}\\{1}", Path, artist);
            Directory.CreateDirectory(dirpath);

            
            foreach (Uri uri in uris)
            {
                string nameValue = _uniDict.FirstOrDefault(x => x.Value == uri.ToString()).Key + ".mp3";
                string path = string.Format("{0}\\{1}",dirpath, nameValue);

                _uniDict[_uniDict.FirstOrDefault(x => x.Value == uri.ToString()).Key] = path;

                var song = _uniDict.FirstOrDefault(x => x.Value == path).Key;
                DownloadingEvent(song);
                try
                {
                    webClient.DownloadFile(uri, path);
                    var tagWorker = new TagWorker();
                    tagWorker.SetTags(path, artist, song);
                    DownloadedEvent(song);
                }
                catch (Exception)
                {
                    //supress
                    FaildeEvent(song);
                }
                
            }

        }

        /// <summary>
        /// Returns URL from
        /// Vk.com audio serch
        /// </summary>
        /// <param name="artist">Artist name</param>
        /// <param name="song">Song name</param>
        /// <returns></returns>
        private static string GetFileUrl(string artist, string song)
        {
            try
            {
                return Vk.GetSongUrl(artist + " - " + song);
            }
            catch (Exception)
            {
                return "NoSongSuchLikeThisLOL";
            }
        }
    }
}